package cn.org.xuanzp.nty.server.adapter;

import cn.org.xuanzp.common.command.Command;
import cn.org.xuanzp.common.command.impl.LoginCommand;
import cn.org.xuanzp.nty.server.handler.CommandHandler;
import cn.org.xuanzp.nty.utils.NettyServerUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * @Classname NettyServerHandler
 * @Description 数据传输操作
 * @Version 1.0.0
 * @Date 2024/9/22 16:41
 * @Created by xuanzp
 */
public class NettyServerHandler  extends ChannelInboundHandlerAdapter {

    private CommandHandler commandHandler;

    public NettyServerHandler(CommandHandler commandHandler) {
        this.commandHandler = commandHandler;
    }

    // 连接上后应该直接传输一个
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
//        super.channelActive(ctx);
        System.out.println("FtpCommandHandler...............channelActive,channel().id="+ctx.channel().id().asLongText());

    }

    // 开始读取的操作
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            Command command = (Command) msg;
            if(command instanceof LoginCommand){
                ((LoginCommand)command).setCtx(ctx);
            }
            commandHandler.handler(command);
//            Object obj = command;
//            ctx.channel().writeAndFlush(obj);// 这里必须传递Object否则客户端出现不接收的问题
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(msg);
        }

    }

    // 出现异常的情况
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause);
    }

}

